package com.unitd.frame.comm.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;

/**
 * @desc 获取系统环境变量工具类
 * @filename EnvUtils.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2016-10-12
 */
public class EnvUtils {

	private static final Logger logger = LoggerFactory.getLogger(EnvUtils.class.getName());

	private static Boolean OS_LINUX = null;

	public static String SYS_DEF_ENCODING = CharsetUtils.UTF_8.name();

	/**
	 * @desc 判断当前系统是否为 linux
	 * @return true linux, false windows
	 */
	public static boolean isLinux() {
		if (OS_LINUX == null) {
			/* 获取应用当前运行的操作系统环境 */
			String OS = System.getProperty("os.name").toLowerCase();
			logger.info("os.name: " + OS);

			if(StringUtils.isEmpty(OS) && OS.contains("windows")) {
				OS_LINUX = false;
			} else {
				OS_LINUX = true;
			}
		}
		return OS_LINUX;
	}

	/**
	 * @desc 返回当前系统变量的函数并将结果放至 Properties
	 * @return
	 */
	public static Properties getEnv() {
		Properties prop = new Properties();
		try {
			Process p;
			if (isLinux()) {
				p = Runtime.getRuntime().exec("sh -c set");
			} else {
				// windows
				p = Runtime.getRuntime().exec("cmd /c set");
			}
			BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String line;
			while ((line = br.readLine()) != null) {
				int i = line.indexOf("=");
				if (i > -1) {
					String key = line.substring(0, i);
					String value = line.substring(i + 1);
					prop.setProperty(key, value);
				}
			}
			br.close();
		} catch (Exception e) {
			throw ExceptionUtils.unchecked(e);
		}
		return prop;
	}
}